/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.alibaba.druid.mock.MockBlob;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.service.*;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


/**
 * 用户Controller
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/agent")
public class AgentaAddController extends BaseController {

	@Autowired
	private SystemService systemService;
	@Autowired
	private AgentAddService agentAddService;
	@Autowired
	PC service;// 调用业务层方法
	@Autowired
	private CommunityService communityService;

	@ModelAttribute
	public User get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getUser(id);
		}else{
			return new User();
		}
	}
	@RequestMapping(value = "/agentAddList")
	public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = agentAddService.findUser(new Page<User>(request, response), user);
        model.addAttribute("page", page);
		if(page.getList().size()==0){
			model.addAttribute("message1","无查询结果");
		}
		return "modules/sys/agentAddList";
	}

	//修改或添加页面
	@RequestMapping(value = "form")
	public String form(User user, Model model) {
		if (user.getCompany()==null || user.getCompany().getId()==null){
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice()==null || user.getOffice().getId()==null){
			user.setOffice(UserUtils.getUser().getOffice());
		}
		List proviceList=service.showProvinceList();
		if(user.getId()!=null){
			UserArea us=new UserArea();
			us.setId(user.getId());
			UserArea userArea=communityService.getAreaByUserId(us);
			model.addAttribute("area",userArea);
		}
		if(!UserUtils.getUser().getId().equals("1")){
			for(int i=0;i<proviceList.size();i++){
				Provinces provinces=(Provinces)proviceList.get(i);
				if(provinces.getProvinceid().equals("111111")){
					proviceList.remove(i);
					i--;
				}
			}
		}
		model.addAttribute("proList",proviceList );// 存入作用域中
		model.addAttribute("user", user);
		return "modules/sys/agentAddForm";
	}
	//修改配送费
	@RequestMapping(value = "tenementPackagefee")
	public String tenementPackagefee(User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		user=systemService.getUser(UserUtils.getUser().getId());;
		model.addAttribute("user",user);
		agentAddService.updatePackagefee(user);
		model.addAttribute("message","保存物业折算比例成功");
		return "modules/sys/tenementPackagefee";
	}
	//修改或添加页面
	@RequestMapping(value = "view")
	public String view(User user, Model model) {
		if (user.getCompany()==null || user.getCompany().getId()==null){
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice()==null || user.getOffice().getId()==null){
			user.setOffice(UserUtils.getUser().getOffice());
		}
		User use=systemService.getUser(user.getId());
		if(user.getId()!=null){
			UserArea us=new UserArea();
			us.setId(user.getId());
			UserArea userArea=communityService.getAreaByUserId(us);
			model.addAttribute("area",userArea);
		}
		model.addAttribute("use",use);
		model.addAttribute("proList", service.showProvinceList());// 存入作用域中
		model.addAttribute("user", user);
		return "modules/sys/agentAddView";
	}
	//添加或修改商户，店铺
	@RequestMapping(value = "save")
	public String save(User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
		user.setCompany(new Office(user.getProvinces()));
		user.setOffice(new Office(user.getProvinces()));
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(user.getNewPassword())) {
			user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
		}
		if (!beanValidator(model, user)){
			return form(user, model);
		}
		if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
			addMessage(model, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
			return form(user, model);
		}
		// 保存用户信息
		agentAddService.saveUser(user);
		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
			UserUtils.clearCache();
			//UserUtils.getCacheMap().clear();
		}
		addMessage(redirectAttributes, "保存代理商'" + user.getLoginName() + "'成功");
		return "redirect:" + adminPath + "/sys/agent/agentAddList";
	}
	/**
	 * 验证登录名是否有效
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName !=null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}
	/**
	 * 删除商户
	 * @param user
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "delete")
	public String delete(User user, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/shopuser/ShopUserList";
		}
		if (UserUtils.getUser().getId().equals(user.getId())){
			addMessage(redirectAttributes, "删除商户失败, 不允许删除当前用户");
		}else if (User.isAdmin(user.getId())){
			addMessage(redirectAttributes, "删除商户失败, 不允许删除超级管理员用户");
		}else{
			systemService.deleteUser(user);
			addMessage(redirectAttributes, "删除代理商成功");
		}
		return "redirect:" + adminPath + "/sys/agent/agentAddList";
	}

	@RequestMapping("/checkAgentAreas")
	public void checkAgentAreas(HttpServletRequest request, HttpServletResponse response,String pid,String cityid){
		response.setContentType("text/html;charset=UTF-8");
		User user=new User();
		user.setProvinces(pid);
		user.setCitys(cityid);
		int rows=systemService.checkAgentAreas(user);
		try{
			if(rows>0){
				response.getWriter().print("1");
			}else{
				response.getWriter().print("0");
			}
			response.getWriter().flush();
			response.getWriter().close();
		}catch (Exception e){
			e.printStackTrace();
		}


	}
	/**
	 * 启用或禁用代理商
	 * @param user
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "updateLoginFlag")
	public String updateLoginFlag(User user, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		if (UserUtils.getUser().getId().equals(user.getId())){
			addMessage(redirectAttributes, "禁用代理商失败, 不允许禁用当前用户");
		}else if (User.isAdmin(user.getId())){
			addMessage(redirectAttributes, "禁用代理商失败, 不允许禁用超级管理员用户");
		}else{
			if(user.getLoginFlag().equals("0")){
				user.setLoginFlag("1");
			}else{
				user.setLoginFlag("0");
			}
			systemService.updateLoginFlag(user);
			if(user.getLoginFlag().equals("0")){
				addMessage(redirectAttributes, "冻结代理商成功");
			}else{
				addMessage(redirectAttributes, "解冻代理商成功");
			}

		}
		return "redirect:" + adminPath + "/sys/agent/agentAddList";
	}
	//代理商流水
	@RequestMapping(value ="mpWalletStream")
	public String mpWalletStream(TbMpWalletStream tbMpWalletStream, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TbMpWalletStream> page = agentAddService.mpWalletStream(new Page<TbMpWalletStream>(request, response), tbMpWalletStream);
		model.addAttribute("walletpage", page);
		return "modules/sys/agentMpWalletStream";
	}
}
